package com.rover.system.service;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.apache.commons.lang.StringUtils;
import org.hibernate.service.spi.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.common.Common;
import com.google.common.base.Charsets;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.io.Files;
import com.grid.DataGrid;
import com.grid.Page;
import com.rover.system.dao.BaseDao;
import com.rover.system.entity.Role;
import com.rover.system.entity.User;


@Service
@Transactional
public class RoleService {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private BaseDao dao;

	@Autowired
	private IdentityService identityService;

	 @Autowired
	 private UserService userService;

	 @Autowired
	 private PermissionService permissionService;
	
	 

	    @Transactional
	    public Role getRoleByName(String roleName){
	        Map<String, Object> params = new HashMap<String, Object>();
	        params.put("roleName", roleName);
	        List<Role> roles = dao.<Role>findHql("from Role where name = :roleName",params);
	        if (roles.size() > 0){
	            return roles.get(0);
	        }
	        return null;
	    }
	
	@Transactional
	public DataGrid query(Page page) throws Exception {
        DataGrid dataGrid=new DataGrid();
        page.setWhere(" name!='"+Common.ADMIN_NAME+"'");
        dataGrid.setResult(dao.<Role>findPageHql(page.getHQL(),page.getWhereParams(), page.getPageNo(),
				page.getPageSize()));
        dataGrid.setTotalCount(dao.countHql(page.getHQLTotalCount(),page.getWhereParams()));
		return dataGrid;
	}

	 @Transactional
	    public List<Role> getRoleListByLoginName(String loginName) {
	        User user = userService.getUserByUserName(loginName);
	        return new ArrayList( user.getRoleList());
	    }
	
	/*
	 * 获取
	 */
	@Transactional
	public List<Role> geList() {
		String hql = "from Role" ;
		return dao.<Role>findHql(hql,null);
	}
	
	
	@Transactional
	public void save(Role role) {
		// 修改的时候删除原有资源
        dao.saveOrUpdate(role);
		String[] strResources = role.getResources().split(";");
//		for (int i = 0; i < strResources.length; i++) {
//			// 第一个是root-0节点，不要填入数据库
//			if (i > 0) {
//				RoleResource rr = new RoleResource();
//				rr.setRole_ID(role.getId());
//				rr.setResource_ID(Integer.valueOf(strResources[i]));
//                dao.save(rr);
//			}
//		}
		
		//同步activiti
         Group group = identityService.newGroup(role.getId().toString());
         group.setName(role.getName());
         group.setType("");
         identityService.saveGroup(group);
	}
    @Transactional
    public void update(Role role) {
        // 修改的时候删除原有资源
        if (role.getId() != null) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("role_ID", role.getId());
            dao.executeHql(
                    "delete RoleResource t where t.role_ID=:role_ID", params);
        }

        Role tRole=   dao.<Role>findHql("from Role where id='"+role.getId()+"'",null).get(0);
         //更新的时候主键应该不能修改，如果修改了，那对应的UserRole数据就会混乱
        dao.update(role);
//        if(role.getpId()==tRole.getpId())     {
//            dao.update(role);
//        }
//          else
//        {
//            dao.delete(tRole);
//            String oldId=role.getId();
//            String newId=getNextId(role.getpId());
//            role.setId(newId);
//            dao.save(role);
//            dao.executeHql("update Role SET id=concat('" + newId + "',substring(id,"+oldId.length()+"+1,length(id))) where substring(id,1,length('" + oldId + "'))='" + oldId + "'",null);
//
//        }
        //保存资源
        String[] strResources = role.getResources().split(";");
        for (int i = 0; i < strResources.length; i++) {
            // 第一个是root-0节点，不要填入数据库
//            if (i > 0) {
//                RoleResource rr = new RoleResource();
//                rr.setRole_ID(role.getId());
//                rr.setResource_ID(Integer.valueOf(strResources[i]));
//                dao.save(rr);
//            }
        }
    }
	/*
	 * 删除数据
	 * @id 要删除的id号
	 * */
	@Transactional
	public void delete(Integer id) {
		//不能这么删除，原因是删了以后，UserRole,Roleresource里的数据都要软套了
//		 Map<String, Object> params = new HashMap<String, Object>();
//		    params.put("id", id+"%");
//        dao.executeHql("delete from Role where id like :id",params);
dao.delete(Role.class, id);
identityService.deleteGroup(id.toString());
    }

	/*
	 * 获取角色id对应的资源名称和id号 返回结果是一个list 0是名称，1是对应的id
	 * @role_ID 要获取资源的Id号
	 * */
	@SuppressWarnings("unchecked")
	@Transactional
	public List<Object> getRoleResourceName(Integer role_ID) {
//		Query q = roleResourceDao
//				.getCurrentSession()
//				.createQuery(
//						"select new list(r.text ,r.id) from Resource r,  RoleResource rr where r.id=rr.resource_ID and rr.role_ID=:role_ID");
//		q.setLong("role_ID", role_ID);
//		return q.list();
		String hql="select new list(r.text ,r.id) from Resource r,  RoleResource rr where r.id=rr.resource_ID and rr.role_ID=:role_ID";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("role_ID", role_ID);
	  return	dao.findHql(hql, params);
	}

	/*
	 * 添加的时候判断名称是否重复
	 * 
	 * @name 要判断的name
	 */
	@Transactional(readOnly = true)
	public Boolean isAddNameRepeat(String name) {
		 Map<String, Object> params = new HashMap<String, Object>();
		    params.put("name",name);
		List<Role> li = dao.findHql("from Role where name=:name", params);
		if (li.size() > 0) {
			return true;
		} else
			return false;
	}

	/*
	 * 编辑的时候判断名称是否重复
	 * 
	 * @name 要判断的name
	 */
	@Transactional(readOnly = true)
	public Boolean isEditNameRepeat(String name, Integer id) {
		 Map<String, Object> params = new HashMap<String, Object>();
		    params.put("name",name);
		    params.put("id",id);
		List<Role> li = dao.findHql("from Role where name=:name and id<>:id", params);
		if (li.size() > 0) {
			return true;
		} else
			return false;
	}


   
	
	 //初始
	@Transactional
    public void initData() throws ServiceException{
		
        logger.debug("开始装载角色初始数据");
        File resourcetxt = new File(this.getClass().getResource("/data/role.txt").getFile());
        String star[] = {};
        try {
            List<String> lines = Files.readLines(resourcetxt, Charsets.UTF_8);

            Role re;
            int line = 1;
            for (String thisLine : lines) {
                //第一行是标题
                if (line == 1) {
                    line++;
                    continue;
                }

                Iterable<String> s = Splitter.on(",").split(thisLine);
                star = Iterables.toArray(s, String.class);

                if (star[0].trim().equals(""))
                    continue;
                
                List<Role> roles = dao.findHql("from Role where name='"+star[0].trim()+"'",null);
                if (roles != null && roles.size() != 0) {
                    continue;
                }
                re = new Role();
                re.setName(star[0].trim());
                re.setDescription(star[1].trim());

                this.dao.save(re);
            }
        } catch (Exception e) {
            logger.error("str[]:" + StringUtils.join(star, ","));
            logger.error("装载角色数据出错:" + e);
            throw new ServiceException("导入角色时，服务器发生异常");
        } finally {
           
        }
    }

}
